package com.jack.payment.util.auth;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AuthUtils {
    // 加密算法类型
    private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding";

    // 前端密钥
    private static final String FRONT_KEY = "e4ea89835ad64eb1b8d76069e33908d4";
    // 前端 偏移量
    private static final String FRONT_IV = "ff465fdecc764337";

    // DB 数据库偏移量
    private static final String IV_KEY = "QWERTYUIOPZXCVBN";
    // DB 密钥 (需要前端和后端保持一致)
    private static final String KEY = "ASDFGHJKLZXCVBNM";


    //算法(恢复有ECB加解密方式，微厅，手厅需要用)
    private static final String ALGORITHMSTRCSS = "AES/ECB/PKCS5Padding";

    public static final int SALT_LENGTH = 6;

    public static String md5Hex(String password, String salt) {
        return md5Hex(password + salt);
    }

    public static String md5Hex(String str) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        byte[] bs = md5.digest(str.getBytes());
        StringBuffer md5StrBuff = new StringBuffer();
        for (int i = 0; i < bs.length; ++i) {
            if (Integer.toHexString(255 & bs[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(255 & bs[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(255 & bs[i]));
            }
        }
        return md5StrBuff.toString();
    }

    /**
     * aes解密 数据库
     * @param encrypt   内容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt) {
        try {
            return aesDecrypt(encrypt, KEY, IV_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * aes加密 数据库
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content) {
        try {
            return aesEncrypt(content, KEY, IV_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    /**
     * aes加密 返回前端数据
     * @param content
     * @return
     * @throws Exception
     */
    public static String frontAesEncrypt(String content) {
        try {
            return aesEncrypt(content, FRONT_KEY, FRONT_IV);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * aes解密 前端传过来的值
     * @param encrypt   内容
     * @return
     * @throws Exception
     */
    public static String frontAesDecrypt(String encrypt) {
        try {
            return aesDecrypt(encrypt, FRONT_KEY, FRONT_IV);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * AES加密为base 64 code
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey, String offsetValue){
        try {
            return base64Encode(aesEncryptToBytes(content, encryptKey, offsetValue));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 将base 64 code AES解密
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey, String offsetValue) throws Exception {
        return encryptStr == null || encryptStr.trim().length() <= 0  ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey, offsetValue);
    }


    /**
     * AES加密
     * @param content 待加密的内容
     * @param encryptKey 加密密钥
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey, String offsetValue) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        IvParameterSpec iv = new IvParameterSpec(offsetValue.getBytes("UTF-8"));
        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes("UTF-8"), "AES"),iv);
        return cipher.doFinal(content.getBytes("utf-8"));
    }



    /**
     * AES解密
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey 解密密钥
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey, String offsetValue) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        IvParameterSpec iv = new IvParameterSpec(offsetValue.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes("UTF-8"), "AES"),iv);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes,"UTF-8");
    }


    // 手机号码前三后四中间脱敏 格式 176****9901
    public static String mobileDesensitization(String mobile) {
        if (mobile != null && mobile.trim().length() > 0 ) {
            return mobile;
        }
        //十一位数直接脱敏
        if (mobile.length() == 11) {
            return mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        } else {
            //非十一位数为AES加密后的，需要解密后脱敏
            return aesDecrypt(mobile).replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
    }


    /**
     * base 64 encode
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes){
        return Base64.getMimeEncoder().encodeToString(bytes);
    }
    /**
     * base 64 decode
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception{
        return base64Code == null || base64Code.trim().length() <= 0 ? null : Base64.getMimeDecoder().decode(base64Code);
    }
}
